package gsw.tool.http;

import java.util.ArrayList;
import java.util.List;

import gsw.tool.http.call.Call;
import gsw.tool.http.call.Dispatcher;
import gsw.tool.http.chain.Interceptor;
import gsw.tool.http.connection.HttpConnectionPool;
import gsw.tool.http.request.Request;

/**
 * 网络请求工具类
 */
public class HttpClient {
    //调度器，用来分发请求任务
    private Dispatcher dispatcher;
    //连接池，用来管理Socket连接
    private HttpConnectionPool httpConnectionPool;
    //请求重试次数，默认重试3次
    private int retrys;
    //拦截器
    private List<Interceptor> interceptors = new ArrayList<>();

    public HttpClient(Builder builder) {
        dispatcher = builder.dispatcher;
        httpConnectionPool = builder.httpConnectionPool;
        retrys = builder.retrys;
        interceptors = builder.interceptors;
    }

    public Call newCall(Request request) {
        return new Call(this, request);
    }

    public int retrys() {
        return retrys;
    }

    public Dispatcher dispatcher() {
        return dispatcher;
    }

    public HttpConnectionPool connectionPool() {
        return httpConnectionPool;
    }

    public List<Interceptor> interceptors() {
        return interceptors;
    }

    /**
     * HttpClient的构建者，用于在HttpClient外部实现HttpClient的属性，并且通过链式调用来设置属性
     */
    public static final class Builder {
        //调度器，用来分发请求任务
        Dispatcher dispatcher;
        //连接池，用来管理Socket连接
        HttpConnectionPool httpConnectionPool;
        //请求重试次数，默认重试3次
        int retrys = 3;
        //拦截器
        List<Interceptor> interceptors = new ArrayList<>();

        public Builder dispatcher(Dispatcher dispatcher) {
            this.dispatcher = dispatcher;
            return this;
        }

        public Builder connectionPool(HttpConnectionPool httpConnectionPool) {
            this.httpConnectionPool = httpConnectionPool;
            return this;
        }

        public Builder retrys(int retrys) {
            this.retrys = retrys;
            return this;
        }

        public Builder addInterceptor(Interceptor interceptor) {
            interceptors.add(interceptor);
            return this;
        }

        /**
         * 创建HttpClient
         */
        public HttpClient build() {
            if (null == dispatcher) {
                dispatcher = new Dispatcher();
            }
            if (null == httpConnectionPool) {
                httpConnectionPool = new HttpConnectionPool();
            }
            return new HttpClient(this);
        }
    }
}
